package server;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

/**
 * Minicat的主类
 */
public class Bootstrap {


    private List<Service> serviceList = new ArrayList<>();


    /**
     * Minicat启动需要初始化展开的一些操作
     */
    public void start() throws Exception {
        loadServerConfig();
        if (serviceList.size() == 0) {
            throw new RuntimeException("no service config");
        }
        for (Service service : serviceList) {
            new Thread(() -> {
                try {
                    service.start();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }).start();
        }
    }

    /**
     * 解析 server.xml
     */
    private void loadServerConfig() {
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("server.xml");
        SAXReader saxReader = new SAXReader();
        try {
            Document document = saxReader.read(resourceAsStream);
            Element rootElement = document.getRootElement();
            List<Element> serviceNode = rootElement.selectNodes("Service");
            for (Element e : serviceNode) {
                List<Element> connectorNode = e.selectNodes("Connector");
                int port = Integer.parseInt(connectorNode.get(0).attributeValue("port"));
                Mapper mapper = new Mapper();
                List<Element> engineNode = e.selectNodes("Engine");
                List<Element> hostNode = engineNode.get(0).selectNodes("Host");
                for (Element hn : hostNode) {
                    String host = hn.attributeValue("name");
                    String appBase = hn.attributeValue("appBase");
                    mapper.setHost(new Mapper.Host(host, new Mapper.Context(appBase)));
                }
                serviceList.add(new Service(port, mapper));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }




    /**
     * Minicat 的程序启动入口
     * @param args
     */
    public static void main(String[] args) {
        Bootstrap bootstrap = new Bootstrap();
        try {
            // 启动Minicat
            bootstrap.start();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
